/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.ss.config.configrations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.zfes.snowy.common.nosql.redis.jedis.SingleWorkerJedisManager;
import org.zfes.snowy.common.nosql.redis.jedis.SnowyJedisManager;
import org.zfes.snowy.ss.config.custom.RedisCustomSerializer;
import org.zfes.snowy.ss.config.properties.ZfesSnowyConfigProperties;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Protocol;

@Configuration
public class RedisSingleConfigration {
	@Autowired
	private ZfesSnowyConfigProperties snowyConfigProperties;
		@Bean
		@Lazy(true)
		public SnowyJedisManager JedisManager(){
			SingleWorkerJedisManager jedisManager=new SingleWorkerJedisManager();
			jedisManager.setJedisPool( getJedisPool());
			return jedisManager;
		}
		 @Lazy(true)
		 @Bean
	     public JedisPool getJedisPool(){  
			 JedisConnectionFactory factory =getConnectionFactory();
			 String host= factory.getHostName();
			 String password=factory.getPassword();
			 int port=factory.getPort();
			 int timeout=factory.getTimeout();
			 JedisPool jedisPool = new JedisPool(factory.getPoolConfig(), host, port, timeout, password, Protocol.DEFAULT_DATABASE, null);
	         return jedisPool;  
	     }
		 @Lazy(true)
		// @ConfigurationProperties(prefix="spring.redis")
	 	 @Bean  
	     public JedisConnectionFactory getConnectionFactory(){  
	         JedisConnectionFactory factory = new JedisConnectionFactory();  
	         return factory;  
	     }
	 	 
	 	@Lazy(true)
	    @SuppressWarnings("rawtypes")
		@Bean
	    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
	        RedisTemplate<String, Object> template = new RedisTemplate<String,Object>();
	        template.setConnectionFactory(getConnectionFactory());
	        template.setKeySerializer(new RedisCustomSerializer<String>(snowyConfigProperties.getSerializeType()));
	        template.setValueSerializer(new RedisCustomSerializer(snowyConfigProperties.getSerializeType()));
	        return template;
	    }
}
